package com.vpx.server.controller.system;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.vpx.server.bean.order.base.BaseDelOrder;
import com.vpx.server.bean.order.base.BaseIdStrOrder;
import com.vpx.server.bean.order.system.ProjectFlowOrder;
import com.vpx.server.bean.order.system.ProjectFlowPageOrder;
import com.vpx.server.bean.order.system.TemplateOrder;
import com.vpx.server.bean.order.system.TemplatePageOrder;
import com.vpx.server.bean.result.system.*;
import com.vpx.server.framework.authority.AuthPoicy;
import com.vpx.server.framework.authority.RequestAuth;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.service.system.ProjectFlowService;
import com.vpx.server.service.system.SqlExtService;
import com.vpx.server.service.system.SqlService;
import com.vpx.server.service.system.TemplateService;
import com.vpx.server.utils.UserLoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工程管理
 */
@RestController
@RequestMapping(value = "/api/template")
@Api(tags = "协议模板管理")
public class TemplateController {

    @Autowired
    private TemplateService templateService;
    @Resource
    private SqlExtService sqlExtService;
    @Resource
    SqlService sqlService;
    @PostMapping("/insertTemplate")
    @ApiOperation("新增协议模板")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg insert(@Validated @RequestBody TemplateOrder order) {
        return templateService.saveTemplate(order);
    }

    @DeleteMapping("/deleteTemplate")
    @ApiOperation("删除协议模板")
    @RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg deleteTemplate(@Validated @RequestBody BaseDelOrder order) {
        return templateService.deleteTemplate(order);
    }

    @PostMapping("/updateTemplate")
    @ApiOperation("修改协议模板")
    @RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg updateById(@RequestBody TemplateOrder order) {
        return templateService.updateTemplateById(order);
    }

    @GetMapping("/selectTemplateById")
    @ApiOperation("查询工程流程")
    @RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<TemplateResult> selectById(BaseIdStrOrder order) {
        return templateService.selectTemplateById(order);
    }

    @GetMapping("/pageQueryTemplate")
    @ApiOperation("分页查询模版")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<TemplatePageResult> pageQueryTemplate(TemplatePageOrder order) {

        return templateService.pageQueryTemplate(order);
    }


    @GetMapping("/templateDetailAttrList")
    @ApiOperation("模板详情与属性列表查询")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<TemplateDetailListResult> templateDetailAttrList(@RequestParam(value = "templateId") String templateId) {

        return templateService.templateDetailAttrList(templateId);
    }

    @PostMapping("/templateAttrSaveUpdate")
    @ApiOperation("模板详情与属性列表保存修改")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg templateAttrSaveUpdate(@RequestBody TemplateOrder order) {

        return templateService.templateAttrSaveUpdate(order);
    }


    @GetMapping("/templateList")
    @ApiOperation("协议模版列表")
    public ResultMsg templateList(@RequestParam(value = "template_type") String template_type) {
        return ResultMsg.success(sqlExtService.findListObject("select id,template_name from c_template where template_type = '"+template_type+"'", JSONObject.class));
    }

    @GetMapping("/templateTool")
    @ApiOperation("工具箱控件数据")
    public ResultMsg templateTool(@RequestParam(required = false) @ApiParam(value = "类型", name = "template_type") String template_type,
                                  @RequestParam(required = false)  @ApiParam(value = "关键字", name = "key_word") String key_word,
                                  @RequestParam(required = false)  @ApiParam(value = "分类ID数组", name = "c_types") List<String> c_types) {
        String sql = "select id,template_name,template_icon,template_type from c_template where template_type = '"+template_type+"'";
        if(StringUtils.isNotBlank(key_word)) {
            sql = sql + " template_name like '"+key_word+"'";
        }
        return ResultMsg.success(sqlExtService.findListObject(sql, JSONObject.class));
    }
    @GetMapping("/findIcons")
    @ApiOperation("获取ICOND")
    public ResultMsg<List<JSONObject>> findIcons() {
        List<JSONObject> list = sqlExtService.findListObject("select attach_id,file_name from sys_attach where operator_name = 'che'",JSONObject.class);
        return ResultMsg.success(list);
    }


    @GetMapping("/stepTool")
    @ApiOperation("流程步工具箱控件数据")
    public ResultMsg templateTool(@RequestParam(required = false)  @ApiParam(value = "1测试用例2流程步8分支", name = "typeCode") String typeCode) {
        String sql = null;
        String toolSql = null;
        if("2".equals(typeCode)) {
            sql = "select id,type_name name from c_type where type_code = '"+typeCode+"' and id not in ('3ed74995dccb4239adc56520e5c33c86','0da30e7d08cb47bd9b22c01705b4df0e')";
            toolSql = "select id,template_name,template_code,template_icon,template_type,type_id,id template_id from c_template  where type_id in (select id from c_type where type_code = '"+typeCode+"' and id not in ('3ed74995dccb4239adc56520e5c33c86','0da30e7d08cb47bd9b22c01705b4df0e'))";
        } else if("8".equals(typeCode)) {
            sql = "select id,type_name name from c_type where type_code = '"+typeCode+"'";
            toolSql = "select id,instance_name template_name,(select template_code from c_template where id = '1e2ac3227f7c2bc959138e0974f5dc94') template_code," +
                    "(select template_icon from c_template where id = '1e2ac3227f7c2bc959138e0974f5dc94') template_icon,'7' template_type,type_id,'1e2ac3227f7c2bc959138e0974f5dc94' template_id " +
                    " from c_project_flow_instance  where type_id in (select id from c_type where type_code = '"+typeCode+"')";
        } else if("1".equals(typeCode)) {
            sql = "select id,type_name name from c_type where type_code = '"+typeCode+"'";
            toolSql = "select id,instance_name template_name,(select template_code from c_template where id = '254081f422f94978645111951a65e9f4') template_code," +
                    "(select template_icon from c_template where id = '254081f422f94978645111951a65e9f4') template_icon,'1' template_type,type_id ,'254081f422f94978645111951a65e9f4' template_id" +
                    " from c_project_flow_instance  where type_id in (select id from c_type where type_code = '"+typeCode+"')";
        }

        //查询分类
        List<JSONObject> types = sqlExtService.findListObject(sql, JSONObject.class);
        //查询分类下的工具
        List<JSONObject> tools = sqlExtService.findListObject(toolSql, JSONObject.class);
        Map<String, List<JSONObject>> toolMaps = CollStreamUtil.groupBy(tools, item -> (String) item.getStr("type_id"), Collectors.toList());
        List<JSONObject> result = new ArrayList<>();
        if(CollUtil.isNotEmpty(types)) {
            types.forEach(type->{
                List<JSONObject> children = toolMaps.get(type.getStr("id"));
                if(CollUtil.isNotEmpty(children)) {
                    type.putByPath("children",children);
                } else {
                    type.putByPath("children",new ArrayList<JSONObject>());
                }
                result.add(type);
            });
        }
        return ResultMsg.success(result);
    }

    @GetMapping("/transTemplate")
    @ApiOperation("同步数据模版属性")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg transTemplate(@RequestParam(value = "templateId") String templateId) {
        //删除引用了当前数据c_base_info_attr的数据
        this.sqlExtService.execute("delete from c_base_info_attr where template_id = '"+templateId+"' and template_attr_id in (select t.template_attr_id from c_template_tran t where t.template_id = '"+templateId+"'  and t.add_type = '2')");
        //新增数据添加
        List<JSONObject> attrs = this.sqlExtService.findListObject("select cbi.id base_info_id,ct.type_id type_code,cta.id template_attr_id,cta.* from c_template_tran ctt,c_base_info cbi,c_template_attr cta,c_template ct " +
                "where ctt.template_id = '" + templateId + "'  and ctt.add_type = '1' and ctt.template_id = cbi.template_id " +
                " and  not EXISTS (select 1 from c_base_info_attr bia where bia.template_id = '" + templateId + "'  and bia.template_attr_id = ctt.template_attr_id) " +
                " and ctt.template_attr_id = cta.id and cta.template_id = ct.id",JSONObject.class);
        List<JSONObject> baseInfoAttrs = new ArrayList<>();
        for(int i = 0; i < attrs.size(); i++) {
            JSONObject attr = attrs.get(i);
            String template_attr_id = attr.getStr("id");
            attr.putByPath("id", IdUtil.getSnowflakeNextIdStr());
            attr.putByPath("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
            attr.putByPath("create_time", DateUtils.getDateTimeStr());
            baseInfoAttrs.add(attr);
        }
        if(baseInfoAttrs.size() > 0) {
            //批量保存数据
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("list", baseInfoAttrs);
            this.sqlService.execute("7", paramMap);
        }
        //删除c_template_tran表数据
        this.sqlExtService.execute("delete from c_template_tran where template_id = '" + templateId + "'");
        return ResultMsg.success("同步成功");
    }
}
